const { SendStatusType } = require("../types/index.js")
const { success, repeatError, noUser, fail, serverError, loginTimeout, commonError } = SendStatusType
const { sendResult } = require("../utils/index.js")

const express = require("express");
const loginRouter = express.Router();

const mysql = require("mysql");
const db = mysql.createPool({
  host: "127.0.0.1",
  user: "root",
  password: "admin123",
  database: "mydatabase_01",
  port: 3306,
});

//登录
loginRouter.post("/login", (req, res) => {
  const { userName, password, remember } = req.body;
  let sql = `SELECT * FROM userinfo WHERE userName = ?`;
  db.query(sql, [userName], (err, result) => {
    if (err) {
      console.log(err);
    }
    if (result.length <= 0) {
      //用户不存在
      sendResult(res, {
        msg: "用户不存在",
      }, noUser);
    } else {
      //找到用户
      if (req.session.isLogin && result[0].isLogin) {
        //排除已登录的情况
        sendResult(res, {
          msg: "已经登录了",
        }, repeatError);
      } else if (result[0].password !== password) {
        //密码错误的情况
        sendResult(res, {
          msg: "密码错误",
        }, fail);
      } else {
        //登录成功
        req.session.isLogin = true;
        req.session.userId = result[0].id;
        let sql = `UPDATE userinfo SET isLogin = 1 WHERE userName = ?`;
        db.query(sql, [userName], (err, result) => {
          if (err) {
            console.log(err);
            return
          }
        })
        sendResult(res, {
          msg: "登录成功",
          token: "token",
        })
      }
    }

  })
});

//获取用户信息
loginRouter.post("/userInfo", (req, res) => {
  let sql = `SELECT * FROM userinfo WHERE id = ?`;
  db.query(sql, [req.session.userId], (err, result) => {
    if (err) {
      console.log(err);
    }

    if (req.session.isLogin && result[0].isLogin) {
      if (req.body.token) {
        sendResult(res, {
          userInfo: {
            ...result[0],
            password: "******",
          },
        }, success);
      } else {
        sendResult(res, {
          msg: "token错误",
        }, commonError);
      }
    } else {
      sendResult(res, {
        msg: "登录过期!"
      }, loginTimeout);
    }
  })

});

//登出
loginRouter.get("/logout", (req, res) => {
  let sql = `UPDATE userinfo SET isLogin = 0 WHERE id = ?`;
  db.query(sql, [req.session.userId], (err, result) => {
    if (err) {
      console.log(err);
      return
    }
  })
  req.session.destroy(); // 清除session
  sendResult(res, {
    msg: "退出登录成功",
  }, success);
});

//修改密码
loginRouter.post('/editpwd', (req, res) => {
  let sql1 = `UPDATE userinfo SET password = ? WHERE id = ?`
  let sql2 = `SELECT * FROM userinfo WHERE id = ?`

  const { password, userName, newPassword, id } = req.body
  if (!password || !newPassword) {
    sendResult(res, {
      msg: '数据不完整!'
    }, commonError)
    return
  }
  db.query(sql2, [id], (err, result) => {
    if (err) {
      console.log('错误');
      return
    }
    if (result.length > 0) {
      if (result[0].password !== password) {
        sendResult(res, {
          msg: '原密码错误!'
        }, fail)
        return
      }
      db.query(sql1, [newPassword, id], (err, result) => {
        if (err) {
          console.log(err);
          return
        }
      })
      sendResult(res, {
        msg: '成功'
      })
      return
    }
  })

})

//修改个人信息
loginRouter.post('/editinfo', (req, res) => {
  let sql = `UPDATE userinfo SET nickName = ?, age = ?, gender = ?, phone = ? , imageUrl = ? , userName = ? WHERE id = ?`
  const { nickName, age, gender, phone, userName, imageUrl, id } = req.body
  if (!nickName || !age || !userName || !phone || !gender || !imageUrl) {
    sendResult(res, {
      msg: '数据不完整!'
    }, commonError)
    return
  }
  console.log(req.body);

  db.query(sql, [nickName, age, gender, phone, imageUrl, userName, id], (err, result) => {
    if (err) {
      console.log(err);
      return
    }
    sendResult(res, {
      msg: '成功'
    })
    return
  })
})


module.exports = loginRouter;
